package com.bjb.vr.remote.task;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.ResGroup;
import com.bjb.vr.common.dto.SysConfig;
import com.bjb.vr.common.mapper.ResGroupMapper;
import com.bjb.vr.common.service.ResGroupService;
import com.bjb.vr.common.service.SysConfigService;
import com.bjb.vr.common.utils.DateTimeUtil;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.remote.ws.rabbitmq.constants.MessageActionConstants;
import com.bjb.vr.remote.ws.rabbitmq.constants.RabbitmqConstants;
import com.bjb.vr.remote.ws.rabbitmq.entity.RabbitWebSocketMsg;
import com.bjb.vr.remote.ws.rabbitmq.utils.MQUtil;
import com.bjb.vr.remote.ws.websocket.constants.WebSocketConstants;
import com.bjb.vr.remote.ws.websocket.entity.Action;
import com.bjb.vr.remote.ws.websocket.entity.Command;
import com.bjb.vr.remote.ws.websocket.entity.StopClassParameter;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @version 1.0.0
 * @author:
 * @time: 2022/4/2 14:26
 */
@Slf4j
@Component
public class RemoteXxlJob {


    @Autowired
    ResGroupMapper resGroupMapper;

    @Autowired
    SysConfigService sysConfigService;

    @Autowired
    ResGroupService resGroupService;

    /**
     * 下课任务
     *
     * @throws Exception
     */
    @XxlJob(value = "stopJobHandler")
    public void execute() throws Exception {
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        LambdaQueryWrapper<ResGroup> queryWrapper = Wrappers.lambdaQuery(ResGroup.class);
        queryWrapper.ne(ResGroup::getContentId,"-1");
        //1:上课 2:下课 -1:初始状态
        queryWrapper.eq(ResGroup::getClassState,"1");
        //教师端websocket连接标识 1:连接 0:断开
        queryWrapper.eq(ResGroup::getAdmConState,0);

        List<ResGroup> resGroupList = resGroupMapper.selectList(queryWrapper);
        if(resGroupList==null || resGroupList.isEmpty()){
            return;
        }
        resGroupList.forEach(resGroup -> {
            int offlineTime = 60;
            if(StringUtils.isEmpty(resGroup.getTenantId())){
                log.error("执行stopJobHandler出错,tenantId为空,设备组名 " + resGroup.getGroupName());
                return;
            }

            LambdaQueryWrapper<SysConfig> configLambdaQueryWrapper = Wrappers.lambdaQuery(SysConfig.class);
            configLambdaQueryWrapper.eq(SysConfig::getTenantId,resGroup.getTenantId());
            SysConfig sysConfig = sysConfigService.getOne(configLambdaQueryWrapper);
            if(sysConfig!=null && sysConfig.getOfflineTime()>0){
                offlineTime = sysConfig.getOfflineTime();
            }
            //教师端离线时间在当前时间和在当前时间-设置下线时间间
            if(resGroup.getAdmOffTime().compareTo(DateTimeUtil.getBeforeSecond(offlineTime))>0){
                return;
            }
            //教师端离线时间小于等于当前时间-设置下线时间间
            Action action = new Action();
            action.setAction(MessageActionConstants.MESSAGE_ACTION_STOP_CALSS);
            Command command = new Command<>();
            StopClassParameter parameter = new StopClassParameter();
            parameter.setId(resGroup.getContentId());
            command.setParameter(parameter);
            action.setCommand(command);

            RabbitWebSocketMsg rabbitWebSocketMsg = new RabbitWebSocketMsg();
            rabbitWebSocketMsg.setIsAdmin("1");
            rabbitWebSocketMsg.setGroupCode(resGroup.getGroupCode());
            String msg = JSONObject.toJSONString(action);
            rabbitWebSocketMsg.setMsg(msg);
            sendRabbitmqTextMsg(rabbitWebSocketMsg);

            resGroup.setClassState(2);
            resGroup.setSectionNo(-1);
            resGroup.setSoundState(-1);
            resGroup.setLockState(-1);
            resGroup.setPlayState(-1);
            resGroup.setCtrlModeState(-1);
            resGroup.setTimeline(-1);
            resGroupService.updateResGroupByGroupCode(resGroup);
        });

    }


    private void sendRabbitmqTextMsg(RabbitWebSocketMsg rwsc){
        rwsc.setDeviceId(rwsc.getGroupCode());
        rwsc.setIsAdmin("1");
        rwsc.setMsgType(WebSocketConstants.WEBSOCKET_CLIENT_MSG_TYPE_TEXT);
        rwsc.setMsg(rwsc.getMsg());
        String json = JSONObject.toJSONString(rwsc);
        MQUtil.send(RabbitmqConstants.FANOUT_WEBSOCKET_EXCHANGE,"", json);
    }

}
